<script setup>
import DataTable from '@/components/table/DataTable.vue'
import EditDialog from '@/components/dialog/EditDialog.vue'
import AddDialog from '@/components/dialog/AddDialog.vue'
import DeleteDialog from '@/components/dialog/DeleteDialog.vue'
import { onMounted, ref } from 'vue';
import userApi from '../api/userApi'

// 表头配置 - 完善表头配置
const headers = [
  { key: 'id', title: 'ID', align: 'center', width: 80 },
  { key: 'username', title: '用户名', align: 'start' },
  { key: 'phoneNumber', title: '手机号', align: 'center' },
  { key: 'role', title: '角色', align: 'center' },
  { key: 'createdAt', title: '创建时间', align: 'center' },
  { key: 'updatedAt', title: '更新时间', align: 'center' },
  { key: 'actions', title: '操作', align: 'center', sortable: false, width: 120 }
]

// 数据和状态管理
const data = ref([])
const loading = ref(false)
const total = ref(0)
const pageSize = ref(10)

// 对话框状态管理
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const currentEditItem = ref(null)
const currentDeleteId = ref(null)
const currentDeleteName = ref('')
const dialogLoading = ref(false)

// 消息提示状态
const snackbar = ref(false)
const snackbarText = ref('')
const snackbarColor = ref('success')

// 表单字段配置
const formFields = [
  {
    key: 'username',
    label: '用户名',
    type: 'text',
    required: true,
    placeholder: '请输入用户名',
    rules: [
      (v) => v?.length >= 2 || '用户名至少2个字符',
      (v) => v?.length <= 20 || '用户名不能超过20个字符'
    ]
  },
  {
    key: 'phoneNumber',
    label: '手机号',
    type: 'text',
    required: true,
    placeholder: '请输入手机号',
    rules: [
      (v) => /^1[3-9]\d{9}$/.test(v) || '请输入有效的手机号'
    ]
  },
  {
    key: 'role',
    label: '角色',
    type: 'select',
    required: true,
    placeholder: '请选择角色',
    options: [
      { title: '医护人员', value: 'medical_staff' },
      { title: '患者', value: 'patient' },
      { title: '家属', value: 'family_member' }
    ]
  }
]

// 新增和编辑都使用相同的表单字段配置（后端自动处理密码）
const editFormFields = formFields

// 搜索下拉选项配置 - 更新为实际的角色枚举值
const selectOptions = [
  {
    key: '角色',
    item: [
      { title: '医护人员', value: 'medical_staff' },
      { title: '患者', value: 'patient' },
      { title: '家属', value: 'family_member' }
    ],
    placeholder: '请选择角色'
  }
]

// 获取用户数据
function getUserData(searchParams = {}) {
  loading.value = true
  const params = {
    pageNumber: 1,
    pageSize: pageSize.value,
    ...searchParams // 合并搜索参数
  }

  userApi.getPage(params).then(res => {
    console.log(res)
    data.value = res.records
    total.value = res.total
  })
  .catch(error => {
    console.log(error)
    // 可以添加错误提示
    data.value = []
  })
  .finally(() => {
    loading.value = false
  })
}

// 搜索处理
const handleSearch = (searchParams) => {
  console.log('搜索参数:', searchParams)
  getUserData(searchParams)
}

// 显示消息提示
const showMessage = (text, color = 'success') => {
  snackbarText.value = text
  snackbarColor.value = color
  snackbar.value = true
}

// 新增用户
const handleAdd = () => {
  addDialogVisible.value = true
}

// 保存新增用户
const handleAddSave = async (formData) => {
  try {
    dialogLoading.value = true
    await userApi.saveOrUpdate(formData)
    addDialogVisible.value = false
    getUserData() // 刷新列表
    showMessage('用户新增成功', 'success')
  } catch (error) {
    console.error('新增用户失败:', error)
    showMessage('新增用户失败，请重试', 'error')
  } finally {
    dialogLoading.value = false
  }
}

// 编辑处理
const handleEdit = (item) => {
  console.log('编辑用户:', item)
  currentEditItem.value = { ...item }
  editDialogVisible.value = true
}

// 保存编辑用户
const handleEditSave = async (formData) => {
  try {
    dialogLoading.value = true
    // 将ID添加到表单数据中，后端根据ID判断是新增还是编辑
    const dataWithId = {
      ...formData,
      id: currentEditItem.value.id
    }
    await userApi.saveOrUpdate(dataWithId)
    editDialogVisible.value = false
    getUserData() // 刷新列表
    showMessage('用户更新成功', 'success')
  } catch (error) {
    console.error('更新用户失败:', error)
    showMessage('更新用户失败，请重试', 'error')
  } finally {
    dialogLoading.value = false
  }
}

// 删除处理
const handleDelete = (item) => {
  console.log('删除用户:', item)
  currentDeleteId.value = item.id
  currentDeleteName.value = item.username
  deleteDialogVisible.value = true
}

// 确认删除用户
const handleDeleteConfirm = async () => {
  try {
    dialogLoading.value = true
    await userApi.deleteById(currentDeleteId.value)
    deleteDialogVisible.value = false
    getUserData() // 刷新列表
    showMessage('用户删除成功', 'success')
  } catch (error) {
    console.error('删除用户失败:', error)
    showMessage('删除用户失败，请重试', 'error')
  } finally {
    dialogLoading.value = false
  }
}

// 取消对话框
const handleDialogCancel = () => {
  addDialogVisible.value = false
  editDialogVisible.value = false
  deleteDialogVisible.value = false
  currentEditItem.value = null
  currentDeleteId.value = null
  currentDeleteName.value = ''
}

// 页码变化处理
const handlePageChange = (page) => {
  console.log('页码变化:', page)
  // 可以重新获取对应页码的数据
}

onMounted(() => {
  getUserData();
})
</script>

<template>
  <div>
    <DataTable 
      card-title="用户管理"
      :table-headers="headers"
      :table-data="data"
      :total="total"
      :items-per-page="pageSize"
      :loading="loading"
      :input-props="['username', 'phoneNumber']"
      :select-props="selectOptions"
      @search="handleSearch"
      @edit="handleEdit"
      @delete="handleDelete"
      @page-change="handlePageChange"
    >
      <!-- 自定义操作区域 -->
      <template #actions>
        <VBtn 
          color="primary" 
          prepend-icon="mdi-plus"
          @click="handleAdd"
        >
          新增用户
        </VBtn>
      </template>

      <!-- 自定义角色列显示 -->
      <template #item.role="{ item }">
        <VChip 
          :color="getRoleColor(item.role)" 
          size="small" 
          variant="flat"
          :prepend-icon="getRoleIcon(item.role)"
        >
          {{ getRoleText(item.role) }}
        </VChip>
      </template>

      <!-- 自定义时间列显示 -->
      <template #item.createdAt="{ item }">
        {{ formatDate(item.createdAt) }}
      </template>

      <template #item.updatedAt="{ item }">
        {{ formatDate(item.updatedAt) }}
      </template>
    </DataTable>

    <!-- 新增用户对话框 -->
    <AddDialog
      v-model:visible="addDialogVisible"
      title="新增用户"
      :fields="formFields"
      :loading="dialogLoading"
      @save="handleAddSave"
      @cancel="handleDialogCancel"
    />

    <!-- 编辑用户对话框 -->
    <EditDialog
      v-model:visible="editDialogVisible"
      title="编辑用户"
      :fields="editFormFields"
      :data="currentEditItem"
      :loading="dialogLoading"
      @save="handleEditSave"
      @cancel="handleDialogCancel"
    />

    <!-- 删除确认对话框 -->
    <DeleteDialog
      v-model:visible="deleteDialogVisible"
      title="确认删除用户"
      :item-name="currentDeleteName"
      :loading="dialogLoading"
      @confirm="handleDeleteConfirm"
      @cancel="handleDialogCancel"
    />

    <!-- 消息提示 -->
    <VSnackbar
      v-model="snackbar"
      :color="snackbarColor"
      :timeout="3000"
      top
      right
    >
      {{ snackbarText }}
      <template #actions>
        <VBtn
          color="white"
          variant="text"
          @click="snackbar = false"
        >
          关闭
        </VBtn>
      </template>
    </VSnackbar>
  </div>
</template>

<script>
// 角色颜色映射 - 更新为实际的角色枚举值
function getRoleColor(role) {
  const colorMap = {
    'medical_staff': 'blue',    // 医护人员用蓝色
    'patient': 'green',         // 患者用绿色
    'family_member': 'orange'   // 家属用橙色
  }
  return colorMap[role] || 'grey'
}

// 角色文本映射 - 更新为实际的角色枚举值
function getRoleText(role) {
  const textMap = {
    'medical_staff': '医护人员',
    'patient': '患者',
    'family_member': '家属'
  }
  return textMap[role] || role
}

// 角色图标映射
function getRoleIcon(role) {
  const iconMap = {
    'medical_staff': 'mdi-stethoscope',    // 医护人员用听诊器图标
    'patient': 'mdi-account-heart',        // 患者用带心形的用户图标
    'family_member': 'mdi-account-group'   // 家属用用户组图标
  }
  return iconMap[role] || 'mdi-account'
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>